package modele;

import java.io.File;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;

import com.phidgets.InterfaceKitPhidget;
import com.phidgets.PhidgetException;
import com.phidgets.event.SensorChangeEvent;
import com.phidgets.event.SensorChangeListener;

import controleur.Controleur;
import controleur.ControleurDeplacement;


public class JoystickEvent implements SensorChangeListener, Runnable {
	// Variable(s) d'instance
	private InterfaceKitPhidget ifp;
	
	// COntroleur(s)
	public JoystickEvent() {
		try {
			this.ifp= new InterfaceKitPhidget();
		} catch (PhidgetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		this.methode();
		ExecutorService ex = Executors.newFixedThreadPool(1);
		ControleurDeplacement conDep = ControleurDeplacement.getInstance();
		ex.execute(conDep);
	}

	@Override
	public void sensorChanged(SensorChangeEvent sensor) {
		ControleurDeplacement conDep = ControleurDeplacement.getInstance();
		if(sensor.getIndex()==7) {
			conDep.setValeurY(sensor.getValue());
		}
		if(sensor.getIndex()==6) {
			conDep.setValeurX(sensor.getValue());
		}
		if(sensor.getIndex()==0&&sensor.getValue()==0){
			if(Controleur.getInstanceCanard().getCanards().size() > 0 && Controleur.getInstanceCanard().getCanards().get(0).getCoupsRestants() > 0) {
				try {
			          Clip clip = AudioSystem.getClip();
			          AudioInputStream inputStream = AudioSystem.getAudioInputStream(new File("./sons/m4a1.wav"));
			          clip.open(inputStream);
			          clip.start(); 
			        } catch (Exception e) {
			          System.err.println(e.getMessage());
			        }
				int index = Controleur.getInstance().verifTir();
				if (index!=-1){
					Controleur.getInstanceCanard().getCanards().get(index).die();
					try {
						Controleur.getInstanceCanard().getCanards().get(index).getSemaphore().acquire();
						Controleur.getInstance().getFenetre().getPanel().remove(Controleur.getInstanceCanard().getCanards().get(index));
						Controleur.getInstanceCanard().getCanards().remove(index);
						Controleur.getInstance().incrementerScore();
						Controleur.getInstance().getFenetre().repaint();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				if(Controleur.getInstanceCanard().getCanards().size() > 0) {
					Controleur.getInstanceCanard().getCanards().get(0).decrementerCoupsRestants();
				}
			}
		}
	}
	
	public void methode() {
		try {
			ifp.openAny();
			ifp.waitForAttachment();
			
			ifp.addSensorChangeListener(this);
		} catch (PhidgetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		
	}
}
